<?php

class Controller {
	/**
	 * smarty实例
	 * @var Smarty
	 */
	var $view = null;
	
	/**
	 * 语言包
	 * @var array
	 */
	var $LAN = array();
	
	/**
	 * 模板基本路径 
	 * @var string
	 */
	var $template_dir = '';
	
	/**
	 * 模块名，如果存在，则模板即使用此模块名作目录
	 * @var string
	 */
	var $module = 'front';
	
	/**
	 * 此请求的ID
	 * 如果是列表的话，即是列表ID，如果是明细页面的话，就是记录ID等
	 * @var string
	 */
	var $id = null;
	
	/**
	 * 页面Title标签内容，默认为网站的标题
	 * @var string
	 */
	var $page_title = null;
	
	/**
	 * 页面meta标签内的keyword属性，默认为网站标题
	 * @var string
	 */
	var $keywords = null;
	
	/**
	 * 页面description，默认为空
	 * @var string
	 */
	var $description = null;
	
	/**
	 * 分页参数
	 */
	var $page_info = null;
	
	/**
	 * 网站配置，主要是从用户模板目录上加载进来的私有配置
	 * @var array
	 */
	var $site_config = array();
	
	/**
	 * 是否缓存页面
	 * @var boolean
	 */
	var $page_cached = false;
	
	/**
	 * 页面缓存KEY
	 * @var string
	 */
	var $page_cache_key = null;
	
	var $cache = null;
	
	/**
	 * 构造函数
	 */
	function Controller(){
		$this->init_request();
		
		$this->cache = get_cache_service();
		/**
		 * 加载语言包
		 */
		$this->load_lang();
		//初始化视图，设置模板路径
		$this->view = Viewer::get_view();
		
		//如果是调试状态，则删除smarty缓存
		if(YU_DEBUG){
			$cache_dir = ROOT_PATH . '/protected/temp/compiled';
			if(!($mydir=@dir($cache_dir))){
				return;
			}
			while(true){
				$file=$mydir->read();
				if(!$file)
					break;
				$file_path = $cache_dir . '/' . $file;
				if(is_file($file_path)){
					@unlink($file_path);
				}
			}
		}
	}
	
	protected function update_page_cache($key=null){
		if($key === null){
			$key = $this->cache->gen_cache_key(MAIN_DOMAIN, REDIRECT_URL);
		}else{
			$key = $this->cache->gen_cache_key(MAIN_DOMAIN, $key);
		}
		$this->cache->remove($key);
	}
	
	/**
	 * 初始化请求数据
	 */
	private function init_request(){
		//初始化ID
		if(isset($_REQUEST['id'])){
			$this->id = trim($_REQUEST['id']);
		}
	}
	
	/**
	 * 初始化分页，可初始化分页的每页显示数量和分页链接显示数量
	 * @param int $page_size 每页显示记录数
	 * @param int $page_view 分页链接显示链接数量
	 * @param string $page_link_format_fun 格式化分页链接的方法，默认使用系统自带的方法
	 */
	protected function init_page_info($page_size=20, $page_view=2, $page_link_format_fun=null){
		if($this->page_info == null){
			$this->page_info = new PageInfo($page_size, $page_view);
		}
		if($page_link_format_fun!=null && function_exists($page_link_format_fun)){
			$this->page_info->page_link_format_fun = $page_link_format_fun;
		}
		return $this->page_info;
	}
	
	/**
	 * 设置分页总数
	 */
	protected function set_page_total($total){
		if($this->page_info == null){
			$this->page_info = new PageInfo();
		}
		$this->page_info->set_total($total);
		$this->assign('page_info', $this->page_info);
	}
	
	/**
	 * 加载语言包
	 */
	protected function load_lang(){
		$lang_files = array(
			//平台共用语言包
			ROOT_PATH . '/protected/language/'.LANGUAGE.'/common.lang.php',
			//平台APP语言包
			ROOT_PATH . '/protected/language/' . LANGUAGE . '/' . APP . '.lang.php',
			//私有共用语言包
			ROOT_PATH . '/sites/main/' . MAIN_DOMAIN . '/template/language/'.LANGUAGE.'/common.lang.php',
			//私有APP语言包
			ROOT_PATH . '/sites/main/' . MAIN_DOMAIN . '/template/language/' . LANGUAGE . '/' . APP . '.lang.php',
		);
		$this->load_lang_file($lang_files);
	}
	
	/**
	 * 加载语言包文件
	 * @param string/array $file_path
	 */
	private function load_lang_file($lang_file_path){
		if(is_array($lang_file_path)){
			foreach ($lang_file_path as $path){
				$this->load_lang_file($path);
			}
		}else{
			if(is_file($lang_file_path)){
				$language = include $lang_file_path;
				Lang::load($language);
			}
		}
	}
	
	/**
	 * 重新转向到某URL
	 * @param string $url
	 */
	protected function redirect($url){
		header('Location: ' . trim($url));
		exit;
	}
	
	/**
	 * 展示
	 * @param string $name
	 */
	protected function display($name=null){
		if($name==null){
			//如果未指定名称，则使用app_act作为默认模板名称
			$name = APP.'/'.ACT;
		}
		define('TEMPLATE_NAME', $name);//此值用于挂件中用于获取对应的配置使用
		
		//检查是否指定使用哪个版本的模板
		if(isset($_REQUEST['tpl_version'])){
			$tpl_version = trim($_REQUEST['tpl_version']);
			define('TPL_VERSION', $tpl_version);
			$name .= '_' . $tpl_version;
		}
		
		$name .= '.' . TEMPLATE_TYPE;
		//初始化SEO数据
		$this->init_seo();
		
		$base_data = array(
			'domain' 		=> DOMAIN,
			'cache_url'		=> CACHE_URL,
			'main_domain' 	=> MAIN_DOMAIN,
			'site_id'		=> SITE_ID,
			'page_title'	=> $this->page_title,
			'keywords'		=> $this->keywords,
			'description'	=> $this->description,
			'app'			=> APP,
			'act'			=> ACT,
			'site_lang'		=> LANGUAGE,
			'cur_url'		=> REQUEST_URI,
		);
		$this->assign($base_data);

		$base_template_path = USER_TEMPLATE_PATH . ($this->module=='front' ? '' : $this->module . '/');
		if(is_file($base_template_path . $name)){
			$this->template_dir = $base_template_path;
		}else{
			//如果指定的模板不存在，则使用系统默认的模板
			$this->template_dir = ROOT_PATH . '/protected/web/' . $this->module . '/template/';
		}
		if(!is_file($this->template_dir . $name)){
			throw new SmartyException('模板不存在：' . $this->template_dir . $name);
		}
		$this->view->template_dir = $this->template_dir;
		if($this->page_cached){
			//需要静态化
			$content = $this->view->fetch($name);
			$key = $this->cache->gen_cache_key(MAIN_DOMAIN, REDIRECT_URL);
			$this->cache->set($key, $content);
			echo $content;
		}else{
			$this->view->display($name);
		}
		$this->view->free();//释放
	}
	
	/**
	 * 指定变量
	 * @param unknown_type $key
	 * @param unknown_type $value
	 */
	protected function assign($key, $value=null){
		if(is_array($key)){
			//如果$key即是数组，则直接将其指向
			foreach ($key as $k=>$v){
				$this->view->assign($k, $v);
			}
		}elseif(is_object($value)){
			//如果值是一个对象，将对象转换成数组
			$this->view->assign($key, (array)$value);
		}else{
			$this->view->assign($key, $value);
		}
	}
	
	/**
	 * 重新设置视图模板路径
	 * @param string $template_dir 视图路径
	 */
	protected function set_view_template_path($template_dir){
		if(is_dir($template_dir)){
			$this->view->template_dir = $template_dir;
		}
	}
	
	/**
	 * 初始化SEO数据，
	 * 主要是页面的：Keyword/Description/Title
	 */
	protected function init_seo($entity=null){
		global $site_info;
		if($this->page_title == null || $this->keywords == null || $this->description == null){
			$page_seo_config = $this->get_seo_config();
		}
		if(empty($this->page_title)){
			//如果标题为空，尝试加载默认标题
			if(isset($entity['title'])){
				$this->page_title = $entity['title'];
			}elseif(isset($page_seo_config[LANGUAGE]['title'])){
				$this->page_title = $entity[LANGUAGE]['title'];
			}elseif(isset($page_seo_config['title'])){
				//通过配置加载
				$this->page_title = eval_content($page_seo_config['title'], $this->view);
			}else{
				//使用默认的
				if(count($site_info['langs'])===1){
					$this->page_title = $entity['name'] . ' - ' . $site_info['name'];
				}else{
					$this->page_title = $site_info[LANGUAGE]['name'];
				}
			}
		}
	
		if($this->keywords == null){
			//如果标题为空，尝试加载默认
			if(isset($entity['seo_keywords'])){
				$this->keywords = $entity['seo_keywords'];
			}elseif(isset($page_seo_config[LANGUAGE]['seo_keywords'])){
				$this->keywords = $entity[LANGUAGE]['seo_keywords'];
			}elseif(isset($page_seo_config['keywords'])){
				//通过配置加载
				$this->keywords = eval_content($page_seo_config['keywords'], $this->view);
			}else{
				//使用默认的
				$this->keywords = '';
			}
		}
	
		if($this->description == null){
			//如果标题为空，尝试加载默认
			if(isset($entity['seo_description'])){
				$this->description = $entity['seo_description'];
			}elseif(isset($page_seo_config[LANGUAGE]['seo_description'])){
				$this->description = $entity[LANGUAGE]['seo_description'];
			}elseif(isset($page_seo_config['description'])){
				//通过配置加载
				$this->description = eval_content($page_seo_config['description'], $this->view);
			}else{
				//使用默认的
				$this->description = '';
			}
		}
	}
	
	private function get_seo_config(){
		//先从私有目录中加载
		$private_seo_path = USER_TEMPLATE_PATH . 'data/seo/' . APP . '_seo.php';
		$page_seo_config = $this->fix_seo_config($private_seo_path);
		if($page_seo_config!=null){
			return $page_seo_config;
		}
		
		//从公共目录中加载
		$public_seo_path = ROOT_PATH . '/protected/web/' . $this->module . '/seo/' . APP . '_seo.php';
		return $this->fix_seo_config($public_seo_path);
	}
	
	/**
	 * 匹配对应的配置，先从定ID查找，如果没有，再从共用的查找
	 * @param array $seo_config
	 */
	private function fix_seo_config($seo_config_path){
		if(!is_file($seo_config_path)){
			return null;
		}
		$seo_config = require $seo_config_path;
		
		if($this->id != null){
			$seo_config_key = APP . '_' . ACT . '_' . $this->id;
			if(isset($seo_config[$seo_config_key])){
				return $seo_config[$seo_config_key];
			}
		}
		$seo_config_key = APP . '_' . ACT;
		if(isset($seo_config[$seo_config_key])){
			return $seo_config[$seo_config_key];
		}
		return null;
	}

	/**
	 * 检查用户权限
	 * @param unknown_type $act_acl
	 */
	protected function has_priv($act_acl=-1){
		if(is_numeric($act_acl)){
			//如果权限值为一数值时，则直接以当前的App当成namcespace
			if($act_acl < 0){
				return true;
			}
			return ACLHelper::check(APP, $act_acl, $this->user_info['acl']);
		}elseif(is_array($act_acl)){
			//如果是一个权限数组时，比如：array('site' => acl_value);
			foreach ($act_acl as $namespace=>$acl){
				if(!ACLHelper::check(strtolower($namespace), $acl, $this->user_info['acl'])){
					//有一项无权限，则无权限
					return false;
				}
			}
			return true;
		}
		return false;
	}
	
	public function captcha(){
		require_once ROOT_PATH . '/protected/includes/securimage/securimage.php';
		$img = new securimage();
		$img->image_width = 80;
		$img->image_height = 50;
		$img->code_length = 4;
		$img->perturbation = 0.1;
		$img->image_bg_color = new Securimage_Color("#f6f6f6");
		$img->use_transparent_text = true;
		$img->text_transparency_percentage = 10; // 100 = completely transparent
		$img->num_lines = 7;
		$img->line_color = new Securimage_Color("#eaeaea");
//		$img->image_signature = 'phpcaptcha.org';
//		$img->signature_color = new Securimage_Color(rand(0, 64), rand(64, 128), rand(128, 255));
		$img->use_wordlist = false; 
//		$img->show('backgrounds/bg3.jpg'); 
		$img->show();
		
		exit;
	}

	protected function get_request_val($name, $default_value=''){
		if(isset($_REQUEST[$name])){
			return $_REQUEST[$name];
		}else{
			return $default_value;
		}
	}
	
	protected function get_request_int_val($name, $default_value=0){
		if(isset($_REQUEST[$name])){
			return intval($_REQUEST[$name]);
		}else{
			return $default_value;
		}
	}

	/**
	 * 从Requst的Get方法中获取值
	 * @param unknown_type $get_name
	 * @param unknown_type $default_value
	 */
	protected function get_val($get_name, $default_value=''){
		if(isset($_GET[$get_name])){
			return $_GET[$get_name];
		}else{
			return $default_value;
		}
	}
	
	/**
	 * 从Requst的Get方法中获取数值
	 * @param unknown_type $get_name
	 * @param unknown_type $default_value
	 */
	protected function get_int_val($get_name, $default_value=0){
		if(isset($_GET[$get_name])){
			return intval($_GET[$get_name]);
		}else{
			return $default_value;
		}
	}
	
	protected function get_post_val($post_name, $default_value=''){
		if(isset($_POST[$post_name])){
			return $_POST[$post_name];
		}else{
			return $default_value;
		}
	}
	
	protected function get_post_int_val($post_name, $default_value=0){
		if(isset($_POST[$post_name])){
			return intval($_POST[$post_name]);
		}else{
			return $default_value;
		}
	}	
	
	protected function ajax_error($error_info, $data=null){
		if(is_array($error_info)){
			echo json_encode($error_info);
		}else{
			echo json_encode(array(
				'result' => false,
				'info'	=> $error_info,
				'data' => $data
			));
		}
		exit;
	}
	
	protected function ajax_info($msg, $data=null){
		if(is_array($msg)){
			echo json_encode($msg);
		}else{
			echo json_encode(array(
				'result' => true,
				'info'	=> $msg,
				'data' => $data
			));
		}
		exit;
	}
}

?>